<template>
  <scroll-view
    :scroll-y="true"
    :enhanced="true"
    :show-scrollbar="false"
    :refresherEnabled="pulldownEnabled"
    :refresher-triggered="isRefreshing"
    :style="{ height }"
    class="common-scroller"
    @refresherrefresh="onRefresh"
    @scrolltolower="onLoadMore"
  >
    <slot></slot>
    <div v-if="hasMore" class="common-scroller__footer">
      <span class="loading-text">
        {{
          pullUpLoading
            ? "加载中..."
            : hasMore
            ? "上拉加载更多"
            : "没有更多数据了"
        }}
      </span>
    </div>
  </scroll-view>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { CommonScrollerProps } from "./types";

defineOptions({
  name: "common-scroller",
});

const props = withDefaults(defineProps<Partial<CommonScrollerProps>>(), {
  height: "100%",
  pulldownEnabled: true,
  hasMore: false,

  immediatePulldown: false,
});

const emits = defineEmits(["refresh", "loadMore"]);

const isRefreshing = ref(false);
const pullUpLoading = ref(false);

// useLoad(async () => {
//   if (props.immediatePulldown) {
//     // isRefreshing.value = true;
//     await Taro.startPullDownRefresh();
//   }
// });

const onRefresh = () => {
  isRefreshing.value = true;
  emits("refresh", () => {
    isRefreshing.value = false;
  });
};

const onLoadMore = () => {
  const { hasMore } = props;
  if (pullUpLoading.value || !hasMore) return;

  pullUpLoading.value = true;
  emits("loadMore", () => {
    pullUpLoading.value = false;
  });
};
</script>

<style lang="less">
.common-scroller {
  box-sizing: border-box;

  &__footer {
    padding: 20px 0;
    text-align: center;

    .loading-text {
      color: #999;
      font-size: 24px;
    }
  }
}
</style>
